package com.amsp.oa.oademo.service.impl;

import com.amsp.oa.oademo.entity.InternalTransfer;
import com.amsp.oa.oademo.entity.InternalTransferDetail;
import com.amsp.oa.oademo.mapper.InternalTransferMapper;
import com.amsp.oa.oademo.mapper.InternalTransferDetailMapper;
import com.amsp.oa.oademo.service.InternalTransferService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@Service
public class InternalTransferServiceImpl extends ServiceImpl<InternalTransferMapper, InternalTransfer>
        implements InternalTransferService {

    @Autowired
    private InternalTransferDetailMapper detailMapper;

    @Override
    public IPage<InternalTransfer> getPage(Integer pageNum, Integer pageSize, String keyword) {
        LambdaQueryWrapper<InternalTransfer> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.hasText(keyword)) {
            wrapper.like(InternalTransfer::getTransferOutName, keyword)
                    .or()
                    .like(InternalTransfer::getTransferInName, keyword);
        }
        wrapper.orderByDesc(InternalTransfer::getCreateTime);
        return page(new Page<>(pageNum, pageSize), wrapper);
    }

    @Override
    public InternalTransfer getTransferWithDetails(Long id) {
        InternalTransfer transfer = getById(id);
        if (transfer != null) {
            LambdaQueryWrapper<InternalTransferDetail> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(InternalTransferDetail::getTransferId, id);
            transfer.setTransferDetails(detailMapper.selectList(wrapper));
        }
        return transfer;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveTransferWithDetails(InternalTransfer transfer) {
        boolean result = saveOrUpdate(transfer);
        if (result && transfer.getTransferDetails() != null) {
            // 删除原有明细
            if (transfer.getId() != null) {
                LambdaQueryWrapper<InternalTransferDetail> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(InternalTransferDetail::getTransferId, transfer.getId());
                detailMapper.delete(wrapper);
            }
            // 保存新的明细
            for (InternalTransferDetail detail : transfer.getTransferDetails()) {
                detail.setTransferId(transfer.getId());
                detailMapper.insert(detail);
            }
        }
        return result;
    }
}